<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="输入用户真实姓名" style="width: 300px;margin-right: 10px" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-select v-model="listQuery.sort" style="width: 100px;margin-right: 10px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>

      <el-select v-model="listQuery.role" placeholder="等级职位" clearable style="width: 150px;margin-right: 10px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" style="margin-left: 10px;" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-download" @click="uploadDialog = true">
        批量添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        下载
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="人员ID" prop="id" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" align="center" width="120">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}')  }}</span>
        </template>
      </el-table-column>

      <el-table-column label="职位等级" width="80px">
        <template slot-scope="{row}">
           <span>{{ row.role }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination total="10" /> -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="批量添加" :visible.sync="uploadDialog">
      <el-form  label-position="left" label-width="150px" style="width: 300; margin-left:50px;">
        <el-form-item label="下载模板" >
          <el-button v-waves :loading="downloadLoadingT" type="primary" icon="el-icon-download" @click="handleDownloadTemplate">
            下载
          </el-button> 
        </el-form-item>        
        <el-form-item label="请选择Excel文件"> 
          <el-upload
            ref="upload"
            :auto-upload="false"
            :before-upload="beforeUpload"
            action="http://port.iris-monitor.com:9001/user/excel/add"
          >
            <el-button slot="trigger" icon="el-icon-folder-add" type="primary">
              选取文件
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitUpload">
          确认
        </el-button>
      </div>

    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="创建时间" style="width: 300px" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="请选择时间" style="width: 300px" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="temp.passWord" show-password/>
        </el-form-item>
        <el-form-item label="职位等级">
          <el-select v-model="temp.role" class="filter-item" placeholder="请选择" style="width: 300px">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle } from '@/api/article'
import waves from '@/waves' // waves directive
import { parseTime } from '@/utils/index'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total:10,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        role: '',
        sort: '+id'
      },

      sortOptions: [{ label: '顺序', key: '+id' }, { label: '倒序', key: '-id' }],
      statusOptions: ['','普通员工', '高级员工', '管理员'],

      temp: {
        id: undefined,
        timestamp: new Date(),
        userName: '',
        realName: '',
        password: '',
        role: ''
      },
      dialogFormVisible: false,
      uploadDialog: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },

      rules: {
        timestamp: [{ type: 'date', required: true, message: '需要选择时间', trigger: 'blur' }],
        userName: [{ required: true, message: '需要填写用户名', trigger: 'blur' }],
        realName: [{ required: true, message: '需要填写用户真实姓名', trigger: 'blur' }],
        passWord: [{ required: true, message: '需要填写密码', trigger: 'blur' }]
      },
      downloadLoading: false,
      downloadLoadingT: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
      console.log(this.sv)
    },
    beforeUpload(file) {
      let filename=file.name
      var index = filename.lastIndexOf(".");
      var suffix = filename.substr(index+1);
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!(suffix=='xlsx'||suffix =='xls')) {
        this.$message.error('只允许上传Excel文件!');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    getList() {
      this.listLoading = true
      //模拟数据
      this.list=[
        {id: 1, timestamp: new Date(),userName: '张',realName: '张永湛',passWord: '123',role: '普通员工' },
        {id: 2, timestamp: new Date(),userName: '杨',realName: '杨焱景',passWord: '123',role: '高级员工' },
        {id: 3, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '普通员工' },
        {id: 4, timestamp: new Date(),userName: '申',realName: '申璐',passWord: '123',role: '管理员' },
        {id: 5, timestamp: new Date(),userName: '邓',realName: '邓冬梅',passWord: '123',role: '普通员工' },
        {id: 6, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '高级员工' },
        {id: 7, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '普通员工' },
        {id: 8, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '普通员工' },
        {id: 9, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '普通员工' },
        {id: 10, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '管理员' },
        {id: 11, timestamp: new Date(),userName: '鲍',realName: '鲍世龙',passWord: '123',role: '普通员工' },
      ]
      this.listLoading = false
    
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   // Just to simulate the time of the request
      //   setTimeout(() => {
      //     this.listLoading = false
      //   }, 1.5 * 1000)
      // })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
      if(this.listQuery.title!=="")
        this.titleFilter()
      if(this.listQuery.role!=="")
        this.roleFilter()
      //this.getList()
    },

    titleFilter(){
      let temp=[]
      for(let i in this.list){
        let t=this.list[i]
        if(t.realName.search(this.listQuery.title) !=-1){
          temp.push(t)
          //let result = t.realName.search(this.listQuery.title)      
        }
      }
      console.log(temp);
      this.list=temp
    },
    roleFilter(){
      let temp=[]
      for(let i in this.list){
        let t=this.list[i]
        if(t.role==this.listQuery.role)
          temp.push(t)
      }
      this.list=temp
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        timestamp: new Date(),
        userName: '',
        realName: '',
        password: '',
        role: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.list.unshift(this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '人员信息添加成功！',
            type: 'success',
            duration: 2000
          })
          // createArticle(this.temp).then(() => {

          // })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          //修改
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '人员信息修改成功',
            type: 'success',
            duration: 2000
          })
          //updateArticle(tempData).then( ... )
        }
      })
    },
    handleDelete(row, index) {
      // const d = new Date().getTime()
      // const str = d.getTime()
      // const strs=parseTime(str)
      // console.log(d)
      this.list.splice(index, 1)
      this.$notify({
        title: 'Success',
        message: '人员信息删除成功',
        type: 'success',
        duration: 2000
      })

    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['人员ID', '用户名', '真实姓名', '创建时间', '职位等级']
        const filterVal = ['id', 'userName', 'realName', 'timestamp', 'role']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '人员信息表'
        })
        this.downloadLoading = false
      })
    },
    handleDownloadTemplate() {
      this.downloadLoadingT = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['人员ID', '用户名', '真实姓名', '创建时间', '职位等级']
        const data = []
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '人员信息表模板'
        })
        this.downloadLoadingT = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
